<?php
class Silk_Pms_Adminhtml_GiftController extends Mage_Adminhtml_Controller_Action
{
	protected function _initAction()
	{
		$this->loadLayout()->_setActiveMenu("pms/gift")->_addBreadcrumb(Mage::helper("adminhtml")->__("买赠管理"),Mage::helper("adminhtml")->__("买赠管理列表"));

		return $this;
	}

	public function indexAction()
	{
		$this->loadLayout();
	    $this->renderLayout();
	}

	public function editAction(){
		$id = $this->getRequest()->getParam('id');
		$model = Mage::getModel("pms/gift")->load($id);
		if($model && $model->getId()){
			Mage::register("gift_data", $model);
		}
		$this->loadLayout();
	    $this->renderLayout();

	}


	public function massRemoveAction(){
		try {
			$ids = $this->getRequest()->getPost('ids', array());
			foreach ($ids as $id) {
				$model = Mage::getModel("pms/gift");
				$model->setId($id)->delete();
			}
			Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("已删除！"));
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}



	public function massChangeStatusAction(){
		date_default_timezone_set('PRC');
		try{
			$ids = $this->getRequest()->getPost('ids', array());
			$status = $this->getRequest()->getPost('status');
			foreach ($ids as $id) {
				$model = Mage::getModel("pms/gift")->load($id);
				$endat = $model->getToDate();
				$endday = strtotime($endat);
				$today = strtotime(date('Y-m-d H:i:s'));
				if($status==1){
					if($today<$endday){
						$model->setStatus($status);
						Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("编号为".$id."的活动状态已启用"));
					}else{
						Mage::getSingleton("adminhtml/session")->addError("编号为".$id."的活动已过期不能启用");
					}
				}else{
					$model->setStatus($status);
					Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("编号为".$id."的活动状态已禁用"));
				}
				$model->save();
			}
		}
		catch (Exception $e) {
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}

	public function saveAction(){
		$data =$this->getRequest()->getPost();
		$websiteId = $data["website_id"];
		$productId = $data["gift_product_id"];
		if(!$this->hasStock($productId,$websiteId)){
			Mage::getSingleton("adminhtml/session")->addError("赠品库存为缺货状态");
			$this->_redirect('*/*/');
			return;
		}
		Mage::log($websiteId);
		$oldqty = $this->getOldQty($productId,$websiteId);
		$giftqty = $data["gift_qty"];
		if($oldqty<$giftqty){
			Mage::getSingleton("adminhtml/session")->addError("赠品库存不足");
			$this->_redirect('*/*/');
			return;
		}
		$model = Mage::getModel("pms/gift")->load($this->getRequest()->getParam("id"));
		if($model && $model->getId()){
			if(!$model->getStatus()){
				$today = strtotime(date('Y-m-d H:i:s'));
				$endday = strtotime($data["to_date"]);
				if($today>$endday){
					Mage::getSingleton("adminhtml/session")->addError("活动已过期，状态禁用");
				}
			}
		}
		$model = Mage::getModel("pms/gift")
				->addData($data)
				->setId($this->getRequest()->getParam("id"));
		try{
			$model->save();
		}catch(Exception $e){
			Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
		}
		$this->_redirect('*/*/');
	}
	//是否为缺货
	public function hasStock($productId,$websiteId){
		$collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
		$collection->addAttributeToFilter('entity_id',$productId);
		if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
		    $collection->joinField('is_in_stock',
		        'cataloginventory/stock_item',
		        'is_in_stock',
		        'product_id=entity_id',
		        '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
		        'left');
		}
		$product = $collection->getFirstItem();
		return $product->getIsInStock();

	}
	//获取库存
	public function getOldQty($productId,$websiteId){
		$collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
		$collection->addAttributeToFilter('entity_id',$productId);
		if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
		    $collection->joinField('qty',
		        'cataloginventory/stock_item',
		        'qty',
		        'product_id=entity_id',
		        '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
		        'left');
		}
        $product = $collection->getFirstItem();
        return $product->getQty();
	}

		//商品列表
	public function productlistAction(){
		$result = array('error'=>true,'message'=>'');
		$sku = $this->getRequest()->getParam('sku');
		$productId = $this->getRequest()->getParam('product_id');
		$name = $this->getRequest()->getParam('name');


		$websiteId = $this->getRequest()->getParam('websiteId');
		$website = Mage::getModel('core/website')->load($websiteId);
		$storeId = $website->getDefaultStore()->getId();
		$collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect('*');
		if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
		    $collection->joinField('qty',
		        'cataloginventory/stock_item',
		        'qty',
		        'product_id=entity_id',
		        '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
		        'left');
		    $collection->joinField('is_in_stock',
		        'cataloginventory/stock_item',
		        'is_in_stock',
		        'product_id=entity_id',
		        '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
		        'left');
		}
		$collection->joinAttribute(
            'status',
            'catalog_product/status',
            'entity_id',
            null,
            'inner',
            $storeId
        );
	    $collection->joinAttribute(
		    'storename',
		    'catalog_product/name',
		    'entity_id',
		    null,
		    'inner',
		    $storeId
		);
		$collection->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));

		if($sku)
		{
			$collection->addFieldtoFilter('sku',array('like'=>"%".$sku."%"));
		}
		if($name)
		{
			$collection->addAttributeToFilter('storename',array('like'=>"%".$name."%"));
		}
		if($productId){
			$collection->addAttributeToFilter('entity_id',array('like'=>"%".$productId."%"));
		}

		if($collection->count())
        {
        	$datas = array();
        	foreach($collection as $key => $product){
        	    $datas[] = array(
        	        "product_id" => $product->getId(),
        	        "name"       => $product->getStorename(),
        	        "sku"        => $product->getSku(),
        	        "image"      => $this->getImageId($product->getId()),
        	        "qty"        => $product->getQty(),
        	        "stock"      =>$product->getIsInStock()
        	    );
        	}
        }else{
        	$result['message'] ="此商品在此站点不可用或不存在";
        	echo  json_encode($result);
        	return;
        }
        $mask = $this->getRequest()->getParam('mask');
        if($mask==1){
	        $html ="";
	        foreach($datas as $data){
	        $html .= <<<HTML
		        <tr class="parent" >
		        	<td style="width:50px;border-bottom:1px solid #CBD3D4;" class="productId">{$data['product_id']}</td>
		        	<td style="width:50px;border-bottom:1px solid #CBD3D4;" class="productsku">{$data['sku']}</td>
		        	<td style="width:80px;border-bottom:1px solid #CBD3D4;" class="productname">{$data['name']}</td>
		        	<td style="width:80px;border-bottom:1px solid #CBD3D4;" class="image">{$data['image']}</td>
		        	<td style="width:20px;border-bottom:1px solid #CBD3D4;"><span class="addtolist">添加</span></td>
HTML;
			}
        }else{
			$html ="";
			foreach($datas as $data){
			$html .= <<<HTML
	    	<tr class="parent" >
	    	<td style="width:50px;border-bottom:1px solid #CBD3D4;" class="productId" qty ="{$data['qty']}" stock="{$data['stock']}">{$data['product_id']}</td>
	    	<td style="width:50px;border-bottom:1px solid #CBD3D4;" class="productsku">{$data['sku']}</td>
	    	<td style="width:80px;border-bottom:1px solid #CBD3D4;" class="productname">{$data['name']}</td>
	    	<td style="width:80px;border-bottom:1px solid #CBD3D4;" class="image">{$data['image']}</td>
	    	<td style="width:20px;border-bottom:1px solid #CBD3D4;"><span class="addtolistgift">添加</span></td>
HTML;
			}
        }

		$result = array('error'=>false,'message'=>$html);
		echo json_encode($result);

	}


	public function getImageId($id)
	{
	    try {

	        $product = Mage::getModel('catalog/product')->load($id);

	        $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();

	        if($websiteId){
	            $storeId = Mage::getModel('core/website')->load($websiteId)->getDefaultStore()->getId();
	            $product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($id);
	            $productImg = Mage::helper('catalog/image')->init($product,'small_image')->resize(100);
	        }else{
	            $productImg = Mage::helper('catalog/image')->init($product,'small_image')->resize(100);
	        }
	    } catch (Exception $e){

	        Mage::logException($e);

	        $placeHolderImg = Mage::getStoreConfig("catalog/placeholder/small_image_placeholder");

	        if(empty($placeHolderImg)){

	            $productImg = "";

	        }else{

	            $productImg = Mage::getSingleton('catalog/product_media_config')->
	                getBaseMediaUrl(). '/placeholder/' . $placeHolderImg;

	        }

	    }


	    return '<img src="'.$productImg.'">';
	}

	protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('pms/gift');
    }


}